<template>
  <div class="app-container">
<!--    <el-row :gutter="20">-->
      <!-- 用户列表 -->
<!--      <el-col :lg="24" :xs="24">-->
        <div class="toolbar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                  v-model="queryParams.keywords"
                  placeholder="姓名"
                  clearable
                  style="width: 300px;height: 30px"
                  @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="status" >
              <el-select
                  v-model="queryParams.status"
                  placeholder="全部"
                  clearable
                  class="!w-[200px]"
                  style='width: 200px;height: 30px'
              >
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size='large' @click="handleQuery" :icon='Search'
              >搜索</el-button
              >
              <el-button @click="resetQuery" size='large' :icon='Refresh'>
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
            <div class="toolbar" style='margin-bottom: 10px;'>
              <div>
                <el-button
                    size='large'
                    type="primary"
                    :icon='Plus'
                    @click="openDialog('user-form')"
                >新增</el-button
                >
              </div>
            </div>
          <el-table
              v-loading="loading"
              :data="pageData"
              :strip='true'
              :border='true'
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
                key="id"
                label="教练id"
                align="center"
                prop="id"
                width="100"
            />
            <el-table-column
                key="realName"
                label="姓名"
                align="center"
                width="150"
                prop="realName"
            />
            <el-table-column label="性别" align="center" prop="gender" width="100">
              <template #default="scope">
                {{scope.row.gender === 'F' ? '女' : '男'}}
              </template>
            </el-table-column>
            <el-table-column
                label="年龄"
                align="center"
                prop="age"
                width="120"
            />
            <el-table-column
              label="专长"
              align="center"
              prop="domain"
              width="200"
            />
            <el-table-column
              label="简历"
              align="center"
              prop="resume"
              width="200"
              title="resume"
            />
<!--            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{
                    scope.row.status == 1 ? "启用" : "禁用"
                  }}</el-tag>
              </template>
            </el-table-column>-->
            <el-table-column
                label="创建时间"
                align="center"
                prop="createTime"
                width="180"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="updateTime"
              width="180"
            />
            <el-table-column label="操作" fixed="right" >
              <template #default="scope">
                <el-button
                    type="info"
                    size="large"
                    @click="resetPassword(scope.row)"
                    :icon='Refresh'
                >重置密码</el-button
                >
                <el-button
                    type="success"
                    size="large"
                    @click="openDialog('user-form', scope.row.id)"
                    :icon='Edit'
                >编辑</el-button
                >
                <el-button
                    type="warning"
                    size="large"
                    @click="handleDelete(scope.row.id)"
                    :icon='Delete'
                >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-footer class='footer'>
            <el-pagination
                large
                background
                v-model:current-page="pagination.pageNum"
                v-model:page-size="pagination.pageSize"
                :page-count='pagination.pageCount'
                layout='total, prev, pager, next'
                :total='pagination.total'
                class='mt-4'
                style='float: right'
                @change='getPage'
            />
          </el-footer>
<!--        </el-card>-->
<!--      </el-col>-->
<!--    </el-row>-->

    <!-- 弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        :width="dialog.width"
        append-to-body
        @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
          v-if="dialog.type === 'user-form'"
          ref="userFormRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="关联用户" prop="userId">
          <el-input
            v-model="formData.userId"
            :readonly="!!formData.id"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
              v-model="formData.realName"
              :readonly="!!formData.id"
              placeholder="请输入姓名"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择">
            <el-option
                v-for="item in genderList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="formData.age"  :min="1" :max="200" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="薪酬" prop="salary">
          <el-input-number
              v-model="formData.salary"
              :min="1"
              placeholder="请输入薪酬，单位为分"
          />
        </el-form-item>

        <el-form-item label="专长" prop="domain">
          <el-input
              v-model="formData.domain"
              placeholder="请输入专长"
              maxlength="150"
          />
        </el-form-item>

        <el-form-item label="教学经验" prop="resume">
          <el-input
            type="textarea"
            autosize
            clearable
            v-model="formData.resume"
            placeholder="请输入教学经验"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import {
  getUserPage,
  getUserForm,
  deleteUsers,
  addUser,
  updateUser,
  updateUserPassword
} from "@/api/sys/user";
import {getCoachPage,addCoach,updateCoach,deleteCoach,getCoachForm} from '@/api/coach'
// import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/sys/role";
import { Plus, Delete, Edit, Search, Share, Refresh } from '@element-plus/icons-vue'
import type { SysUserForm, SysUserQuery, SysUserPageVO } from "@/api/sys/user/types.ts";
import { type UploadInstance, ElMessageBox, ElMessage, ElForm } from 'element-plus'
import { ref,onMounted,reactive,watch } from "vue";
import type { OptionType } from 'element-plus/es/components/select-v2/src/select.types'
import type { CoachForm,CoachQuery,CoachPageVO } from '@/api/coach/types.ts'

// import zh from 'element-plus/lib/locale/lang/en'
//
// zh.el.pagination.total = '共:{total}条';
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<CoachQuery>({
  pageNum: 1,
  pageSize: 10,
  pages: undefined,
  total: undefined,
});
const total = ref(0); // 数据总数
const pageData = ref<SysUserPageVO[]>(); // 用户分页数据
const roleList = ref<OptionType[]>(); // 角色下拉数据源
const pagination = ref({
  pageNum: 1,pageSize: 10,total: 0,pageCount: 1
});
// watch(dateTimeRange, (newVal) => {
//   if (newVal) {
//     queryParams.startTime = newVal[0];
//     queryParams.endTime = newVal[1];
//   }
// });

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

const genderList = ref<OptionType[]>([{
  label: '男',
  value: 'M',
},{
  label: '女',
  value: 'F'
}
]);

// 用户表单数据
const formData = reactive<CoachForm>({
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  realName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  roleIdList: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  getCoachPage(queryParams)
    .then((resp) => {
      let data = resp.data;
      pageData.value = data.records;
      // total.value = data.total;
      pagination.value.pageNum = data.current
      pagination.value.pageSize = data.size
      pagination.value.total = data.total
      pagination.value.pageCount = data.pages
      // queryParams.pageNum = data.current;
      // queryParams.pageSize = data.size;
    })
    .finally(() => {
      loading.value = false;
    });
}

function getPage(currentPage:number,pageSize :number){
  console.log('currentPage:',currentPage,'pageSize:',pageSize);
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  handleQuery()
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 重置密码 */
function resetPassword(row: { [key: string]: any }) {
  ElMessageBox.prompt(
      "请输入用户「" + row.username + "」的新密码",
      "重置密码",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
  ).then(({ value }) => {
    if (!value) {
      ElMessage.warning("请输入新密码");
      return false;
    }
    updateUserPassword(row.id, value).then(() => {
      ElMessage.success("密码重置成功，新密码是：" + value);
    });
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id 用户ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    // 用户表单弹窗
    // await loadDeptOptions();
    // await loadRoleOptions();
    if (id) {
      dialog.title = "修改教练信息";
      getCoachForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
    } else {
      dialog.title = "新增教练信息";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = 1;
  }
}

/** 表单提交 */
const handleSubmit = (() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        console.log('==========================',userId);
        loading.value = true;
        if (userId) {
          updateCoach(userId, formData)
              .then(() => {
                ElMessage.success("修改用户成功");
                closeDialog();
                resetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
          addCoach(formData)
              .then(() => {
                ElMessage.success("新增用户成功");
                closeDialog();
                resetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    let deleteIds = [];
    if(removeIds.value && removeIds.value.length > 1){
      deleteIds = removeIds.value;
    }else{
      deleteIds.push(id);
    }
    deleteCoach(deleteIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
.toolbar {
padding: 10px 0;
}
<style scoped>
.footer {
  margin-top: 20px;
}
</style>
